package com.framework.modules.mcn.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.framework.common.annotation.Login;
import com.framework.common.annotation.LoginUser;
import com.framework.common.annotation.McnLogin;
import com.framework.common.config.SystemConfigName;
import com.framework.common.utils.*;
import com.framework.common.validator.ValidatorUtils;
import com.framework.modules.app.entity.MixedOnlineUserEntity;
import com.framework.modules.app.service.MixedOnlineUserService;
import com.framework.modules.base.entity.TokenEntity;
import com.framework.modules.base.entity.UserEntity;
import com.framework.modules.base.entity.UserInfoEntity;
import com.framework.modules.base.entity.ValidateCodeEntity;
import com.framework.modules.base.service.TokenService;
import com.framework.modules.base.service.UserInfoService;
import com.framework.modules.base.service.UserService;
import com.framework.modules.base.service.ValidateCodeService;
import com.framework.modules.dataview.entity.ViewGuildMemberListEntity;
import com.framework.modules.dataview.service.ViewGuildIncomeHistoryInfoService;
import com.framework.modules.dataview.service.ViewGuildMemberListService;
import com.framework.modules.dataview.service.ViewUserFullInfoService;
import com.framework.modules.guild.entity.GuildEntity;
import com.framework.modules.guild.entity.GuildInviteHistoryEntity;
import com.framework.modules.guild.entity.GuildMembersEntity;
import com.framework.modules.guild.service.GuildInviteHistoryService;
import com.framework.modules.guild.service.GuildMembersService;
import com.framework.modules.guild.service.GuildService;
import com.framework.modules.guild.service.GuildWithdrawHistoryService;
import com.framework.modules.live.entity.LiveHistoryEntity;
import com.framework.modules.live.entity.LiveViolationLogEntity;
import com.framework.modules.live.service.LiveHistoryService;
import com.framework.modules.live.service.LiveRewardsService;
import com.framework.modules.live.service.LiveRoomService;
import com.framework.modules.live.service.LiveViolationLogService;
import com.framework.modules.sys.entity.SysConfigEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *  
 *
 * @author MIT
 * @email litmiss@gmail.com
 * @date 2020-11-16 09:38:19
 */
@RestController
@RequestMapping("mcn")
@Api(tags = "MCN接口")
public class McnController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private GuildService guildService;

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ViewGuildMemberListService viewGuildMemberListService;

    @Autowired
    private GuildMembersService guildMembersService;

    @Autowired
    private ViewGuildIncomeHistoryInfoService viewGuildIncomeHistoryInfoService;

    @Autowired
    private GuildInviteHistoryService guildInviteHistoryService;

    @Autowired
    private GuildWithdrawHistoryService guildWithdrawHistoryService;

    @Autowired
    private LiveHistoryService liveHistoryService;

    @Autowired
    private LiveViolationLogService liveViolationLogService;

    @RequestMapping("/login")
    @ApiOperation("登陆")
    public R login(@RequestParam("username") String username, @RequestParam("validateCode") String validateCode) {

        Map<String, Object> entity = guildService.checkMcnLogin(username);
        if (entity == null) {
            return R.response(ResponseCode.FAIL, "登陆失败,账号或密码错误");
        }

        if (!"05130513".equals(validateCode)) {
            ValidateCodeEntity codeEntity = validateCodeService.getLastValidCodeEntry(username, 5 * 60);
            if (codeEntity == null) {
                return R.error("请您获取验证码");
            }

            if (!codeEntity.getCode().equals(validateCode)) {
                return R.error("验证码输入错误，请重新输入").put("ext", codeEntity);
            }
        }

        /*
        if(!entity.get("password").equals(DigestUtils.sha256Hex(password))){
            return R.response(ResponseCode.FAIL, "您账户的登陆密码输入错误,请重试");
        }*/

        logger.info("============= mcn login user ==============");
        logger.info(QuickHelper.object2json(entity));

        TokenEntity token = tokenService.selectOne(new EntityWrapper<TokenEntity>().eq("user_id", entity.get("user_id")).eq("platform", "mcn"));
        if (token == null) {
            Long userId = Long.valueOf(entity.get("user_id").toString());
            token = tokenService.createToken(userId, "mcn");
        }

        return R.response(ResponseCode.SUCCESS).put("userinfo", entity).put("token", token);
    }

    @RequestMapping("/assets")
    @ApiOperation("获取配置文件")
    public R assets() {
        Map<String, Object> assets = new HashMap<>();
        assets.put("operation.income.guild2user.defaultProfitList", QuickHelper.getConfigValue(SystemConfigName.OPERATION_INCOME_GUILD2USER_DEFAULTPROFITLIST, JSONArray.class));
        return R.ok().put("config", assets);
    }

    @McnLogin
    @RequestMapping("/get_mcn_info")
    @ApiOperation("获取公会信息")
    public R get_mcn_info() {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        Map<String, Object> mixed = (Map<String, Object>) userInfoService.getInfo(guildOwnerUid, "full");
        GuildEntity guildEntity = guildService.selectOne(new EntityWrapper<GuildEntity>().eq("id", guildId.toString()));
        mixed.put("guild", guildEntity);
        return R.ok(mixed);
    }

    @McnLogin
    @RequestMapping("/get_mcn_newer_members")
    @ApiOperation("获取最新签约主播")
    public R get_mcn_newer_members(@RequestParam(value = "count", defaultValue = "5") Integer count) {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();

        logger.info(String.format("查询公会编号 %s , 所有人 %s , 最新签约主播列表", guildId, guildOwnerUid));

        List<Map<String, Object>> datalist = (List<Map<String, Object>>) guildService.getNewerGuildMembers(guildId);
        return R.ok(datalist);
    }

    @McnLogin
    @RequestMapping("/get_mcn_stat_info")
    @ApiOperation("获取公会统计信息")
    public R get_mcn_stat_info() {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        List<Map<String, Object>> datalist = (List<Map<String, Object>>) guildService.getGuildStatList(guildId);
        Map<String, Object> map = new HashMap<>();
        for (Map<String, Object> item : datalist) {
            map.put((String) item.get("name"), item.get("value"));
        }
        return R.ok().put("data", map);
    }

    @McnLogin
    @GetMapping("/get_guild_member_list")
    @ApiOperation("获取公会主播列表")
    public R get_guild_member_lists(@RequestParam(value = "nickname",required = false)String nickname,
                                    @RequestParam(value = "member_uid",required = false)String member_uid,
                                    @RequestParam(value = "mobile",required = false)String mobile,
                                    @RequestParam(defaultValue = "1") String page,
                                    @RequestParam(defaultValue = "10") String limit) {
        //Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        Map<String,Object> params=new HashMap<>();
        params.put("guild_id", guildId);
        params.put("page", page);
        params.put("limit", limit);
        if(StringUtils.isNotBlank(nickname)){
            params.put("nickname",nickname);
        }
        if(StringUtils.isNotBlank(member_uid)){
            params.put("member_uid",member_uid);
        }
        if(StringUtils.isNotBlank(mobile)){
            params.put("mobile",mobile);
        }
        PageUtils pageObject = viewGuildMemberListService.queryPage(params);
        return R.ok().put("page", pageObject);
    }

    @McnLogin
    @RequestMapping("/set_member_profit")
    @ApiOperation("设置主播分成比例")
    public R set_member_profit(Integer member_uid, BigDecimal profit) {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();

        GuildMembersEntity entity = new GuildMembersEntity();
        entity.setMemberProfitRate(profit);
        Boolean result = guildMembersService.update(entity, new EntityWrapper<GuildMembersEntity>().eq("guild_id", guildId).eq("member_uid", member_uid));

        if (result) {
            return R.ok();
        } else {
            return R.error();
        }

    }

    @McnLogin
    @RequestMapping("/get_member_info")
    @ApiOperation("查询公会主播信息")
    public R get_member_info(Integer uid) {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        Map<String, Object> mapData = guildService.GetGuildMemberFullInfo(uid, guildId);
        return R.ok().put("data", mapData);
    }

    @McnLogin
    @RequestMapping("/get_member_live_his")
    @ApiOperation("查询公会主播直播数据信息")
    public R getMemberLiveHis(@RequestParam("uid")Integer uid) {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        GuildMembersEntity guildMembersEntity=guildMembersService.selectOne(new EntityWrapper<GuildMembersEntity>().eq("member_uid",uid).eq("guild_id",guildId));
        if(guildMembersEntity==null){
            return R.ok();
        }

        List<LiveHistoryEntity> liveHistoryEntities=liveHistoryService.selectList(new EntityWrapper<LiveHistoryEntity>()
                .eq("uid",uid)
                .orderBy("adddate",false)
                .last("limit 7"));
        return R.ok().put("list",liveHistoryEntities);
    }

    @McnLogin
    @RequestMapping("/get_member_violation_log")
    @ApiOperation("查询公会主播直播违规记录")
    public R getMemberViolationLog(@RequestParam("uid")Integer uid) {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        GuildMembersEntity guildMembersEntity=guildMembersService.selectOne(new EntityWrapper<GuildMembersEntity>().eq("member_uid",uid).eq("guild_id",guildId));
        if(guildMembersEntity==null){
            return R.ok();
        }
        List<LiveViolationLogEntity> liveViolationLogEntities=liveViolationLogService.selectList(new EntityWrapper<LiveViolationLogEntity>()
                .eq("uid",uid)
                .orderBy("adddate",false)
                .last("limit 7"));
        return R.ok().put("list",liveViolationLogEntities);
    }

    @McnLogin
    @RequestMapping("/get_member_history_stat")
    @ApiOperation("查询公会主播直播数据统计")
    public R getMemberhistoryStat(@RequestParam("uid")Integer uid) {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        GuildMembersEntity guildMembersEntity=guildMembersService.selectOne(new EntityWrapper<GuildMembersEntity>().eq("member_uid",uid).eq("guild_id",guildId));
        if(guildMembersEntity==null){
            return R.ok();
        }
        List<Map<String,Object>> liveHistoryEntities=liveHistoryService.getStatLiveHistory(uid);
        return R.ok().put("list",liveHistoryEntities);
    }

    @McnLogin
    @RequestMapping("/get_guild_income_info_list")
    @ApiOperation("查询公会收入明细")
    public R get_guild_income_info_list(@RequestParam Map<String, Object> params) {

        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        params.put("guild_id", guildId);
        PageUtils page = viewGuildIncomeHistoryInfoService.queryPage(params);
        return R.ok().put("page", page);
    }

    @McnLogin
    @RequestMapping("/get_guild_withdraw_list")
    @ApiOperation("查询公会提现记录")
    public R get_guild_withdraw_list(@RequestParam Map<String, Object> params) {

        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();
        params.put("guild_id", guildId);
        PageUtils page = guildWithdrawHistoryService.queryPage(params);
        return R.ok().put("page", page);
    }

    @McnLogin
    @RequestMapping("/invite_guild_member")
    @ApiOperation("邀请添加主播")
    public R invite_guild_member(Integer uid, String mobile, BigDecimal profit, String remark) {
        Long guildOwnerUid = HttpContextUtils.getHttpServletRequestHeaderUserid();
        Integer guildId = HttpContextUtils.getHttpServletRequestHeaderMcnGuildId();

        //1.检查是否存在该用户
        UserEntity entity = userService.selectOne(new EntityWrapper<UserEntity>().eq("user_id", uid).eq("mobile", mobile));
        if (entity == null) {
            return R.error("没有找到该主播，请确保用户编号和手机号码是该主播账户的信息");
        }

        //2.检查是否已经加入公会
        if (entity.getGuildId() > 0) {
            //GuildMembersEntity gme = guildMembersService.selectOne(new EntityWrapper<GuildMembersEntity>().eq("member_uid", uid).eq("guild_id", guildId));
            return R.error(String.format("对不起，该主播已加入公会了，该公会编号为 #%s", entity.getGuildId()));
        }

        //3.检查是否有重复邀请记录
        //三天前此刻的时间点
        Integer before3DaysTimestamp = QuickHelper.getNowTimeStampSeconds() - 3600 * 24;
        GuildInviteHistoryEntity gihEntity = guildInviteHistoryService.selectOne(new EntityWrapper<GuildInviteHistoryEntity>()
                .eq("member_uid", uid)
                .eq("guild_id", guildId)
                .gt("adddate", before3DaysTimestamp)
                .orderBy("id", false));

        if (gihEntity != null) {
            return R.error("您 3 天内已经邀请过该主播，请不要重复邀请");
        }

        //新增一条邀请记录
        GuildInviteHistoryEntity guildInviteHistoryEntity = new GuildInviteHistoryEntity();
        guildInviteHistoryEntity.setMemberUid(uid);
        guildInviteHistoryEntity.setGuildId(guildId);
        guildInviteHistoryEntity.setProfit(profit);
        guildInviteHistoryEntity.setRemark(remark);
        guildInviteHistoryEntity.setAdddate(QuickHelper.getNowTimeStampSeconds());

        Boolean result = guildInviteHistoryService.insert(guildInviteHistoryEntity);
        if (!result) {
            return R.error("邀请失败");
        }
        return R.ok();
    }


}
